import router from './router'
import store from './store'
import {Message} from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {getToken, getShopList, setToken, removeToken} from '@/utils/auth'
import {isRelogin} from '@/utils/request'
import {debug} from "script-ext-html-webpack-plugin/lib/common";

NProgress.configure({showSpinner: false})

const whiteList = ['/login', '/auth-redirect', '/bind', '/register']

router.beforeEach((to, from, next) => {
  NProgress.start()
  var bool = process.env.NODE_ENV === 'development';
  if (!bool) {
    if (!getToken()) {
      let token = decodeURIComponent(window.location.search.slice(7))
      setToken(token)
    }
  }
  // console.log('token###', getToken())
  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    if (to.path === '/login') {
      removeToken()
      // next(process.env.VUE_APP_LOGOUT_PATH)
      // NProgress.done()
      window.location.href = process.env.VUE_APP_LOGOUT_PATH;
    } else if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if (store.getters.roles.length === 0) {
        // return;
        isRelogin.show = true
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then((res) => {
          isRelogin.show = false
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            next({...to, replace: true}) // hack方法 确保addRoutes已完成
          })
          store.dispatch('getAliossInfo')
          // store.dispatch('getMarkValue').then()
          // store.dispatch('getCompanyMark').then()
          // store.dispatch('getEvaluationValue').then()
          // store.dispatch('getGroupValue').then()
          // console.log('this.$authFun.getShopList()', getShopList(), store.getters.shopList)
          // let shopList = JSON.parse(store.getters.shopList)
          // console.log('shopList', shopList)
        }).catch(err => {
          // console.log('获取用户信息失败errr', err)
          // removeToken()
          store.dispatch('LogOut').then(() => {
            // location.location.href = process.env.VUE_APP_LOGOUT_PATH;
            next(process.env.VUE_APP_LOGOUT_PATH)
          })
        })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    // console.log('没有token', to)
    // if (bool) {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      // console.log('@@@@@@', process.env.VUE_APP_LOGOUT_PATH)
      // next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      window.location.href = process.env.VUE_APP_LOGOUT_PATH
      // next(process.env.VUE_APP_LOGOUT_PATH) // 否则全部重定向到登录页
      // NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
